package com.mytx.sso.service.impl;


import com.alibaba.fastjson.JSONObject;


import com.mytx.sso.service.MobileCodeService;
import com.mytx.sso.service.SendMobilCodeRetrofitService;
import com.mytx.sso.sms.ConfigManager;
import com.mytx.sso.sms.Message;
import com.mytx.sso.sms.RetrofitManager;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import retrofit2.Response;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.MessageFormat;

@SuppressWarnings("Duplicates")
@Service
public class MobileCodeServiceImpl implements MobileCodeService {
    Logger logger = LoggerFactory.getLogger(MobileCodeServiceImpl.class);
    @Autowired
    ConfigManager configManager;
    @Autowired
    RetrofitManager retrofitManager;

    @Override
    public String sendRegisterMobileCode(String mobile, String code, String custid) throws Exception {
        Message message = new Message();
//        message.setUserid(configManager.getUserid());
//        message.setPwd(configManager.getPwd());
        message.setApikey(configManager.getApikey());
        message.setMobile(mobile);
        String content = MessageFormat.format(
                configManager.getRegisterSmsTemplate(),
                code,
                configManager.getServicePhone());
        try {
            //对短信内容进行编码 urlencode（GBK明文）
            content = URLEncoder.encode(content, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        message.setContent(content);
        if (StringUtils.isNotBlank(custid)) {
            message.setCustid(custid);
        }
        logger.debug(JSONObject.toJSONString(message));
        Response<JSONObject> response = null;
        response = retrofitManager.createReq(SendMobilCodeRetrofitService.class).sendMobileCode(message).execute();

        if (response != null && response.isSuccessful()) {
            JSONObject body = response.body();
            String result = body.getString("result");
            if (result.equals("0")) {
                return MobileCodeService.SEND_MOBIL_CODE_SUCCESS;
            }
            logger.error("发送短信失败：" + result);
            //  return MobileCodeService.SEND_MOBIL_CODE_Fail;

        }
        throw new Exception("发送短信失败" );
        // return MobileCodeService.SEND_MOBIL_CODE_Fail;
    }
}
